﻿///<copyright>
/// Copyright © 2009 Stephen Styrchak. All Rights Reserved.
///</copyright>
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using Ferpect.ComponentModel.Sprites;
using Microsoft.Xna.Framework;

namespace Ferpect.ComponentModel.Design
{
    public class MovementInfoConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;
            if (destinationType == typeof(string))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            // Insert other ConvertTo operations here.
            //
            if (destinationType == typeof(string))
            {
                MovementInfo info = value as MovementInfo;
                if (info != null)
                {
                    return String.Format("({0})", info.Type);
                }
                return String.Empty;
            }

            if (destinationType == typeof(InstanceDescriptor) && value is MovementInfo)
            {
                MovementInfo info = (MovementInfo)value;

                ConstructorInfo ctor = typeof(MovementInfo).GetConstructor(new Type[] { typeof(SpriteMovementType), typeof(float), typeof(float), typeof(Vector2[]) });
                if (ctor != null)
                {
                    return new InstanceDescriptor(ctor, new object[] { info.Type, info.MaxMoveSpeed, info.MaxTurnSpeed, info.WayPoints.ToArray() });
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(value, attributes);
        }
    }
}
